import isEmpty from 'loadsh/isEmpty'
import {
  CORPID,
  SPACEID
} from '/constData/requestFun/_globalData';
import {
  GetContractInfo,
  GetInfoPicture,
  GetPreviewImage,
  PostContractInfo,
  PostDeleteData,
  PostInfoPicture
} from '/constData/requestFun/_httpRequest';
import {
  ContractManagementDeleteData,
  GetContractManagement,
  GetContractManagementById,
  GetContractNum,
  GetMeetingMinutes,
  GetTopic,
  GetTopicById,
  PostContractManagement
} from '/constData/requestFun/_teseRequest';
import compact from 'loadsh/compact'
Page({
  data: {
    item: 1,
    index: 0,
    min: null,
    max: new Date('2033/12/02'),
    defaultDate: new Date(),
    arrIndex: 0,
    index: 0,
    contractinfo: {
      CorpId: '',
      ContractNumber: '', //合同编号
      ConsumableType: '请选择类型', //合同类型
      SignDate: '', //签约日期
      OurCompany: '', //我方单位名称
      OppositeCompany: '', //对方单位名称
      Content: '', //内容
      Picture: '[]', //图片
      Amount: '', //金额
      AssociateOtherId: '[]', //关联审批单
      ApprovalAnnex: '[]', //合同审批附件
      TempTopic: [], //添加议题
    },
    Select1: ['框架协议', '采购合同', '其他合同'],
    ReceiveData: [],
    displayPicture: [],
    displayApprovalAnnex: [],
    position: '',
    animation: true,
    basicVisible: false,
    closeVisible: false,
    DisTopicData: [],
    DisTopicDisplayData: [],
    Select2: [{
        value: '总经理办公会',
        label: '总经理办公会'
      },
      {
        value: '支委会',
        label: '支委会'
      },
      {
        value: '董事会',
        label: '董事会'
      },
      {
        value: '股东会',
        label: '股东会'
      }
    ],
  },
  AddTempTopic() {
    const newTempTopic = {
      ApplicatDepart: '综合部', //申请部门
      TopicTitle: '', //议题标题
      TopicContent: '', //议题论述
      ReviewConference: '支委会', //审议会议
      Participants: '', //提请事项
      Notes: '', //备注
    };
    const addnewTempTopic = this.data.contractinfo.TempTopic.concat([newTempTopic]);
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        TempTopic: addnewTempTopic
      }
    })
    console.log('SSS', addnewTempTopic);
  },
  ApplicatDepartChange(value, e) {
    const TempTopic = this.data.contractinfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].ApplicatDepart = value;
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        TempTopic: TempTopic
      }
    });
  },
  TopicTitleChange(value, e) {
    const TempTopic = this.data.contractinfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].TopicTitle = value;
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        TempTopic: TempTopic
      }
    });
  },
  TopicContentChange(value, e) {
    const TempTopic = this.data.contractinfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].TopicContent = value;
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        TempTopic: TempTopic
      }
    });
  },
  ParticipantsChange(value, e) {
    const TempTopic = this.data.contractinfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].Participants = value;
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        TempTopic: TempTopic
      }
    });
  },
  NotesChange(value, e) {
    const TempTopic = this.data.contractinfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].Notes = value;
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        TempTopic: TempTopic
      }
    });
  },
  onReviewChange(value, e) {
    const TempTopic = this.data.contractinfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].ReviewConference = value.join(',');
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        TempTopic: TempTopic
      }
    });
  },
  DeleteTopic(e) {
    const index = e.currentTarget.dataset.index;
    const addTopic = this.data.contractinfo.TempTopic.filter((_, i) => i !== index);
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        TempTopic: addTopic
      }
    })
  },
  onContractTypeChange(e) {
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        ConsumableType: e
      }
    })
    if (this.data.contractinfo.ConsumableType === '框架协议') {
      GetContractNum((res) => {
        console.log('res', res);
        this.setData({
          contractinfo: {
            ...this.data.contractinfo,
            ContractNumber: 'KJ' + res.data
          }
        })
      })
    } else if (this.data.contractinfo.ConsumableType === '采购合同') {
      GetContractNum((res) => {
        this.setData({
          contractinfo: {
            ...this.data.contractinfo,
            ContractNumber: 'CG' + res.data
          }
        })
      })
    } else if (this.data.contractinfo.ConsumableType === '其他合同') {
      GetContractNum((res) => {
        this.setData({
          contractinfo: {
            ...this.data.contractinfo,
            ContractNumber: 'QT' + res.data
          }
        })
      })
    }

  },
  onAmountChange(e) {
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        Amount: e
      }
    })
  },
  Delete(e) {
    const id = e.currentTarget.dataset.id
    ContractManagementDeleteData(id, (res) => {
      my.alert({
        title: '撤销成功',
      });
      //刷新数据
      this.setData({
        ReceiveData: this.data.ReceiveData.filter((it) => {
          return it.item1.id !== id
        })
      })
    }, (err) => {
      my.alert({
        title: '撤销失败',
      });
    })
  },
  selectorProject(e) {
    const data = e.target.dataset.data
    const newAssociateOtherIds = [
      ...JSON.parse(this.data.contractinfo.AssociateOtherId || '[]'), // 将字符串转换为数组，如果为空则使用空数组  
      data.item1.id // 添加新的ID到数组中  
    ];
    this.setData({
      DisTopicDisplayData: [...this.data.DisTopicDisplayData, data],
      contractinfo: {
        ...this.data.contractinfo,
        AssociateOtherId: JSON.stringify(newAssociateOtherIds) // 将数组转换回字符串，以符合您当前的数据结构  
      }
    })
    my.alert({
      title: '添加成功',
    });
  },
  handlePopupClose() {
    this.setData({
      basicVisible: false,
      scrollVisible: false,
      closeVisible: false,
    });
  },
  handleShowClose() {
    this.setData({
      closeVisible: true
    });
  },
  handleShowBasic(e) {
    var position = e.target.dataset.position;
    this.setData({
      position: position,
      basicVisible: true,
    });
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        GetTopic((res) => {
          const cacheData = res.data.map(it => {
            if (it.item1.corpId === storage.data.result.userid) {
              it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
              return it
            }
          })
          this.setData({
            DisTopicData: compact(cacheData).reverse()
          })
        })
      }
    })
  },
  handleOk(date, format, e) {
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        SignDate: date
      },
    })
  },
  onContractNumberChange(e) {
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        ContractNumber: e
      }
    })
  },
  onOurCompanyChange(e) {
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        OurCompany: e
      }
    })
  },
  onOppositeCompanyChange(e) {
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        OppositeCompany: e
      }
    })
  },
  onContentChange(e) {
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        Content: e
      }
    })
  },
  handleChange(value) {
    this.setData({
      value,
    });
  },
  //获取数据
  onLoad() {
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        new Promise((resolve) => {
          GetContractManagement((res) => {
            const cacheData = res.data.map(it => {
              if (it.item1.corpId === storage.data.result.userid) {
                it.item1['displayPicture'] = JSON.parse(it.item1.picture)
                it.item1['displayApprovalAnnex'] = JSON.parse(it.item1.approvalAnnex)
                it.item1['displayTempTopic'] = JSON.parse(it.item1.tempTopic)

                return it;
              }
            });
            resolve(cacheData);
          });
        }).then((cacheData) => {
          const updatedResPromises = cacheData.map(it => {
            // 将 associateOtherId 从字符串转换为数组，如果是 '[]' 则转换为空数组  
            const associateIds = (typeof it.item1.associateOtherId === 'string' && it.item1.associateOtherId === '[]') ? [] : JSON.parse(it.item1.associateOtherId);
            it.item3 = []
            if (it.item1.corpId === storage.data.result.userid && associateIds.length > 0) {
              // 对每个 associateId 获取 Topic  
              return Promise.all(associateIds.map(associateId => {
                return new Promise((resolve) => {
                  GetTopicById(associateId, (TopicRes) => {
                    it.item3.push(TopicRes.data.item1)
                    resolve(it);
                  });
                });
              })).then(() => it); // 所有 Topic 获取完毕后返回当前对象  
            } else {
              // 如果 associateIds 为空或 it.item1.corpId 不匹配，则直接返回当前对象  
              return Promise.resolve(it);
            }
          });
          // 等待所有 Promise 完成  
          return Promise.all(updatedResPromises).then(updatedRes => {
            this.setData({
              contractinfo: {
                ...this.data.contractinfo,
                CorpId: storage.data.result.userid
              },
              ReceiveData: compact(updatedRes).reverse()
            });
          });
        });
      }
    });
  },
  // 上传数据
  onSubmit(e) {
    //上传时，将TempTopic数组转换为字符串
    this.setData({
      contractinfo: {
        ...this.data.contractinfo,
        TempTopic: JSON.stringify(this.data.contractinfo.TempTopic)
      }
    });
    PostContractManagement(JSON.stringify(this.data.contractinfo),
      (res) => {
        my.getStorage({
          key: 'userInfo',
          success: (storage) => {
            new Promise((resolve) => {
              GetContractManagement((res) => {
                const cacheData = res.data.map(it => {
                  if (it.item1.corpId === storage.data.result.userid) {
                    it.item1['displayPicture'] = JSON.parse(it.item1.picture)
                    it.item1['displayApprovalAnnex'] = JSON.parse(it.item1.approvalAnnex)
                    it.item1['displayTempTopic'] = JSON.parse(it.item1.tempTopic)

                    return it;
                  }
                });
                resolve(cacheData);
              });
            }).then((cacheData) => {
              const updatedResPromises = cacheData.map(it => {
                // 将 associateOtherId 从字符串转换为数组，如果是 '[]' 则转换为空数组  
                const associateIds = (typeof it.item1.associateOtherId === 'string' && it.item1.associateOtherId === '[]') ? [] : JSON.parse(it.item1.associateOtherId);
                it.item3 = []
                if (it.item1.corpId === storage.data.result.userid && associateIds.length > 0) {
                  // 对每个 associateId 获取 Topic  
                  return Promise.all(associateIds.map(associateId => {
                    return new Promise((resolve) => {
                      GetTopicById(associateId, (TopicRes) => {
                        it.item3.push(TopicRes.data.item1)
                        resolve(it);
                      });
                    });
                  })).then(() => it); // 所有 Topic 获取完毕后返回当前对象  
                } else {
                  // 如果 associateIds 为空或 it.item1.corpId 不匹配，则直接返回当前对象  
                  return Promise.resolve(it);
                }
              });
              // 等待所有 Promise 完成  
              return Promise.all(updatedResPromises).then(updatedRes => {
                this.setData({
                  contractinfo: {
                    ...this.data.contractinfo,
                    CorpId: storage.data.result.userid
                  },
                  ReceiveData: compact(updatedRes).reverse()
                });
              });
            });
          }
        });
        my.alert({
          title: '提交成功',
        });
        this.setData({
          contractinfo: {
            ...this.data.contractinfo,
            ContractNumber: '', //合同编号
            ConsumableType: '框架协议', //合同类型
            SignDate: '', //签约日期
            OurCompany: '', //我方单位名称
            OppositeCompany: '', //对方单位名称
            Content: '', //内容
            Picture: '[]', //图片
            Amount: '', //金额
            AssociateOtherId: '[]', //关联审批单
            ApprovalAnnex: '[]', //合同审批附件
            TempTopic: [], //添加议题
          }
        })
      },
      (err) => {
        my.alert({
          title: '提交成功1',
        });
      })
  },

  //上传图片
  onUpload() {
    let imagePicture = ''
    dd.uploadAttachmentToDingTalk({
      image: {
        max: 9,
        spaceId: SPACEID,
        compress: true,
        folderId: '',
        multiple: true,
      },
      types: ['photo'],
      success: (res) => {
        const srcPicture = this.data.contractinfo.Picture
        imagePicture = res.data
        imagePicture.push(...JSON.parse(srcPicture))
        this.setData({
          displayPicture: imagePicture,
          contractinfo: {
            ...this.data.contractinfo,
            Picture: JSON.stringify(imagePicture)
          }
        })
      },
      fail: () => {},
      complete: () => {},
    });
  },
  //上传文件
  onUploadFile() {
    let fileAnnex = ''
    dd.uploadAttachmentToDingTalk({
      types: ['file'],
      file: {
        spaceId: SPACEID,
        max: 9,
        folderId: ''
      },
      success: (res) => {
        const srcApprovalAnnex = this.data.contractinfo.ApprovalAnnex
        fileAnnex = res.data
        fileAnnex.push(...JSON.parse(srcApprovalAnnex))
        this.setData({
          displayApprovalAnnex: fileAnnex,
          contractinfo: {
            ...this.data.contractinfo,
            ApprovalAnnex: JSON.stringify(fileAnnex)
          }
        })
      },
      fail: () => {},
      complete: () => {},
    });
  },
  PreviewBtn(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
  CheckPictures(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },


});